package com.gpframework.common.pay.leshua.service;

import com.gpframework.common.pay.leshua.config.LeshuaConfig;
import com.gpframework.common.pay.leshua.util.*;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author eden
 * @date 2018/5/21 下午3:36
 * @desc
 */
public class GateWayService {
    private static Logger log = LoggerFactory.getLogger(GateWayService.class.getName());

    private HttpClientHelper httpClientHelper = new HttpClientHelper();

    /**
     * <一句话功能简述> <功能详细描述>支付请求
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */
    public void pay(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.debug("支付请求...");
        // SortedMap<String, String> map = XmlUtils.getParameterMap(req);

        SortedMap<String, String> map = new TreeMap<String, String>();
        map.put("service", "get_tdcode");
        map.put("pay_way", "ZFBZF"); // WXZF ZFBZF QQZF UPSMZF
        map.put("third_order_id", "110" + System.currentTimeMillis());
        map.put("amount", "1");
        map.put("jspay_flag", "0");
        // map.put("appid", "");
        // map.put("sub_openid", "");
        map.put("merchant_id", LeshuaConfig.mch_id);
        map.put("notify_url", LeshuaConfig.notify_url);
        map.put("nonce_str", String.valueOf(new Date().getTime()));

        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        log.debug("preStr:{}", preStr);
        String sign = MD5.sign(preStr, "&key=" + LeshuaConfig.key, "utf-8");
        map.put("sign", sign);

        String reqUrl = LeshuaConfig.req_url;
        log.debug("reqUrl：" + reqUrl);

        log.debug("reqParams:" + XmlUtils.parseXML(map));
        String res = httpClientHelper.postForm(reqUrl, map, HttpClientHelper.ACCEPT_TYPE_X_WWW);
        log.debug("请求结果：" + res);
    }


    /**
     * 条码支付
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void authcodePay(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.debug("支付请求...");
        // SortedMap<String, String> map = XmlUtils.getParameterMap(req);

        SortedMap<String, String> map = new TreeMap<String, String>();
        map.put("service", "upload_authcode");
//		map.put("pay_way", "ZFBZF"); // WXZF ZFBZF QQZF UPSMZF
        map.put("third_order_id", "110" + System.currentTimeMillis());
        map.put("amount", "1");
        map.put("auth_code", "135630589181043802");
        // map.put("appid", "");
        // map.put("sub_openid", "");
        map.put("merchant_id", LeshuaConfig.mch_id);
        map.put("notify_url", LeshuaConfig.notify_url);
        map.put("nonce_str", String.valueOf(new Date().getTime()));

        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        log.debug("preStr:{}", preStr);
        String sign = MD5.sign(preStr, "&key=" + LeshuaConfig.key, "utf-8");
        map.put("sign", sign);

        String reqUrl = LeshuaConfig.req_url;
        log.debug("reqUrl：" + reqUrl);

        log.debug("reqParams:" + XmlUtils.parseXML(map));
        String res = httpClientHelper.postForm(reqUrl, map, HttpClientHelper.ACCEPT_TYPE_X_WWW);
        log.debug("请求结果：" + res);
    }

    /**
     * <一句话功能简述> <功能详细描述>订单查询
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */
    public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.debug("订单查询...");
//		SortedMap<String, String> map = XmlUtils.getParameterMap(req);
        SortedMap<String, String> map = new TreeMap<String, String>();

        map.put("service", "query_status");
        map.put("merchant_id", LeshuaConfig.mch_id);
//		map.put("third_order_id", "1101526623184899");//1805181359418947  1101526623184899
        map.put("leshua_order_id", "1805181359418947");//1805181359418947  1101526623184899

        String key = LeshuaConfig.key;
        String reqUrl = LeshuaConfig.req_url;
        map.put("nonce_str", String.valueOf(new Date().getTime()));

        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        String sign = MD5.sign(preStr, "&key=" + key, "utf-8");
        map.put("sign", sign);

        log.debug("reqUrl:" + reqUrl);

        log.debug("reqParams:" + XmlUtils.parseXML(map));
        String res = httpClientHelper.postForm(reqUrl, map, HttpClientHelper.ACCEPT_TYPE_X_WWW);
        try {
            boolean falg = LeshuaSignature.checkIsSignValidFromResponseString(res, resExcludedSignParams(), key);
            log.info("验签结果:{}", falg);
            log.debug("map:{}", LeshuaSignature.getMapFromXML(res));

        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            log.error(e.getMessage());
        }
        log.debug("请求结果：" + res);
    }

    /**
     * 响应结果不参与计算签名的参数
     *
     * @return
     */
    protected Set<String> resExcludedSignParams() {
        Set<String> exludedSignParams = new HashSet<String>(2);
        exludedSignParams.add("sign");
        exludedSignParams.add("resp_code");
        return exludedSignParams;
    }


    /**
     * <一句话功能简述> <功能详细描述>退款查询
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */
    public void refundQuery(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.debug("退款查询...");
//		SortedMap<String, String> map = XmlUtils.getParameterMap(req);
        SortedMap<String, String> map = new TreeMap<String, String>();

        map.put("service", "unified_query_refund");
        String key = LeshuaConfig.key;
        String reqUrl = LeshuaConfig.req_url;
        map.put("merchant_id", LeshuaConfig.mch_id);
        map.put("nonce_str", String.valueOf(new Date().getTime()));
//		map.put("third_order_id", "1101526623184899");//1805181359418947  1101526623184899
        map.put("leshua_order_id", "1805181556518998");//1805181359418947  1101526623184899
        map.put("merchant_refund_id", "1201526630322057");
//		map.put("leshua_refund_id", "1201526630322057");
        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        String sign = MD5.sign(preStr, "&key=" + key, "utf-8");
        map.put("sign", sign);

        log.debug("reqUrl:" + reqUrl);

        String res = httpClientHelper.postForm(reqUrl, map, HttpClientHelper.ACCEPT_TYPE_X_WWW);
        log.debug("请求结果：" + res);
    }

    /**
     * <一句话功能简述> <功能详细描述>退款
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */
    public void refund(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.debug("退款...");
        SortedMap<String, String> map = new TreeMap<String, String>();
        map.put("service", "unified_refund");

        String key = LeshuaConfig.key;
        String reqUrl = LeshuaConfig.req_url;
        map.put("merchant_id", LeshuaConfig.mch_id);
//		map.put("third_order_id", "1101526623184899");//1805181359418947  1101526623184899
        map.put("leshua_order_id", "1805181659419030");//1805181359418947  1101526623184899
        map.put("merchant_refund_id", "120" + System.currentTimeMillis());
        map.put("refund_amount", "1");

        map.put("nonce_str", String.valueOf(new Date().getTime()));

        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        String sign = MD5.sign(preStr, "&key=" + key, "utf-8");
        map.put("sign", sign);

        log.debug("reqUrl:" + reqUrl);

        String res = httpClientHelper.postForm(reqUrl, map, HttpClientHelper.ACCEPT_TYPE_X_WWW);
        log.debug("请求结果：" + res);

    }

    public static void main(String[] args) {

        GateWayService service = new GateWayService();
        try {
//			service.pay(null, null);
            service.query(null, null);
//			service.refund(null,null);
//			service.authcodePay(null, null);
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            log.error(e.getMessage());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            log.error(e.getMessage());
        }
    }

}
